package me.qi.kancha.security;

import com.xhyt.common.resource.TokenConverter;
import com.xhyt.common.resource.support.JwtAccessToken;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * jwt token 转换器
 *
 * @author sun
 * @date 2019/9/27 17:08
 */
@Component
public class JwtTokenConverter extends JwtAccessTokenConverter {

    private static final String SIGNING_KEY = "SUN1024";

    private TokenConverter tokenConverter = new TokenConverter();

    public JwtTokenConverter() {
        super.setSigningKey(SIGNING_KEY);
    }

    @Override
    public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        return tokenConverter.convertAccessToken(token, authentication);
    }

    @Override
    public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
        return tokenConverter.extractAccessToken(value, map);
    }

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        return tokenConverter.extractAuthentication(map);
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        accessToken = super.enhance(accessToken, authentication);
        OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
        Long refreshTokenExp = null;
        if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
            refreshTokenExp = ((ExpiringOAuth2RefreshToken)refreshToken).getExpiration().getTime();
        }
        return new JwtAccessToken(accessToken.getValue(), accessToken.getExpiration().getTime(),
                refreshToken.getValue(), refreshTokenExp);
    }

    /**
     * 使用自身作为转换器，生成token
     *
     * @param oAuth2AccessToken
     * @param authentication
     * @return
     */
    @Override
    public String encode(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication) {
        super.setAccessTokenConverter(this);
        return super.encode(oAuth2AccessToken, authentication);
    }
}
